package com.fun.exception;

import java.util.ArrayList;
import java.util.List;

/**H
 * try catch中触发return时会在栈中开辟一个空间保存结果，然后执行finally。在finally中没有return的情况下：
 * 当返回值为基本类型或者被final修饰的不可变类型时，基本类型返回的就是值，被final修饰的不可变类型，对其进行修改，就变成了另外一个对象了，对源对象没有影响；
 * 当返回值为引用类型并且是没有被final修饰的类型时，返回的是该对象的地址，对该对象进行修改，那就真正的修改了；
 *
 * 异常部分不用测试了，很简单，需要注意的是：finally中避免再次抛出异常，一旦finally中发生异常，代码执行将会抛出finally中的异常信息，try、catch中的异常将被忽略
 */
public class FinallyTest {
    public static void main(String[] args) {
        System.out.println("............我是分隔符呀...........");
        System.out.println("main result1: " + testBasic());
        System.out.println("............我是分隔符呀...........");
        System.out.println("main result2: " + testBasic());
        System.out.println("............我是分隔符呀...........");
        System.out.println("main result3: " + testWrap());
    }

    public static int testBasic() {
        int i = 1;
        try {
            i++;
            System.out.println("try block, i = " + i);
            return i;
        } catch (Exception e) {
            i++;
            System.out.println("catch block i = " + i);
            return i;
        } finally {
            i = 10;
            System.out.println("finally block i = " + i);
        }
    }

    public static List<Object> testWrap() {
        List<Object> list = new ArrayList<>();
        try {
            list.add("try");
            System.out.println("try block");
            return list;
        } catch (Exception e) {
            list.add("catch");
            System.out.println("catch block");
            return list;
        } finally {
            list.add("finally");
            System.out.println("finally block ");
        }
    }

    public static String testBasic2() {
        String i = "a";
        try {
            i="b";
            System.out.println("try block, i = " + i);
            return i;
        } catch (Exception e) {
            i="c";
            System.out.println("catch block i = " + i);
            return i;
        } finally {
            i = "d";
            System.out.println("finally block i = " + i);
        }
    }
}
